package org.jeecg.modules.crm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.crm.entity.CrmCustomer;
import org.jeecg.modules.crm.entity.vo.CrmCustomerVO;
import org.jeecg.modules.crm.service.ICrmCustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 客户信息表
 * @Author: jeecg-boot
 * @Date:   2025-06-03
 * @Version: V1.0
 */
@Slf4j
@Api(tags="客户信息")
@RestController
@RequestMapping("/crm/customer")
public class CrmCustomerController extends JeecgController<CrmCustomer, ICrmCustomerService> {
    @Autowired
    private ICrmCustomerService customerService;
    
    /**
     * 分页列表查询
     */
    @AutoLog(value = "客户信息表-分页列表查询")
    @ApiOperation(value="客户信息表-分页列表查询", notes="客户信息表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CrmCustomer customer,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {
        QueryWrapper<CrmCustomer> queryWrapper = QueryGenerator.initQueryWrapper(customer, req.getParameterMap());
        Page<CrmCustomer> page = new Page<>(pageNo, pageSize);
        IPage<CrmCustomer> pageList = customerService.page(page, queryWrapper);
        return Result.OK(pageList);
    }
    
    /**
     * 添加
     */
    @AutoLog(value = "客户信息表-添加")
    @ApiOperation(value="客户信息表-添加", notes="客户信息表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CrmCustomerVO customerVO) {
        try {
            log.info("客户信息添加: {}", customerVO.getCustomerName());
            
            // 生成客户编号
            if (customerVO.getCustomerCode() == null || customerVO.getCustomerCode().trim().isEmpty()) {
                customerVO.setCustomerCode(generateCustomerCode());
            }
            
            // 处理省市区信息
            validateAreaInfo(customerVO);
            
            boolean success = customerService.saveCustomerVO(customerVO);
            if (success) {
                return Result.OK("添加成功！");
            } else {
                return Result.error("添加失败！");
            }
        } catch (Exception e) {
            log.error("客户信息添加失败", e);
            // 处理唯一性验证异常
            if (e.getMessage().contains("客户名称和联系人组合已存在")) {
                return Result.error("客户名称[" + customerVO.getCustomerName() + "]和联系人[" + customerVO.getContactPerson() + "]组合已存在，请勿重复添加！");
            }
            return Result.error("添加失败：" + e.getMessage());
        }
    }
    
    /**
     * 编辑
     */
    @AutoLog(value = "客户信息表-编辑")
    @ApiOperation(value="客户信息表-编辑", notes="客户信息表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CrmCustomerVO customerVO) {
        try {
            log.info("客户信息编辑: {}", customerVO.getCustomerName());
            
            // 验证客户ID是否存在
            if (customerVO.getId() == null || customerVO.getId().trim().isEmpty()) {
                return Result.error("客户ID不能为空！");
            }
            
            // 处理省市区信息
            validateAreaInfo(customerVO);
            
            boolean success = customerService.updateCustomerVO(customerVO);
            if (success) {
                return Result.OK("编辑成功!");
            } else {
                return Result.error("编辑失败！");
            }
        } catch (Exception e) {
            log.error("客户信息编辑失败", e);
            // 处理唯一性验证异常
            if (e.getMessage().contains("客户名称和联系人组合已存在")) {
                return Result.error("客户名称[" + customerVO.getCustomerName() + "]和联系人[" + customerVO.getContactPerson() + "]组合已存在，请修改后重试！");
            }
            return Result.error("编辑失败：" + e.getMessage());
        }
    }
    
    /**
     * 通过id删除
     */
    @AutoLog(value = "客户信息表-通过id删除")
    @ApiOperation(value="客户信息表-通过id删除", notes="客户信息表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        customerService.deleteCustomerById(id);
        return Result.OK("删除成功!");
    }
    
    /**
     * 批量删除
     */
    @AutoLog(value = "客户信息表-批量删除")
    @ApiOperation(value="客户信息表-批量删除", notes="客户信息表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.customerService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }
    
    /**
     * 通过id查询
     */
    @AutoLog(value = "客户信息表-通过id查询")
    @ApiOperation(value="客户信息表-通过id查询", notes="客户信息表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
        CrmCustomerVO customerVO = customerService.getCustomerVOById(id);
        return Result.OK(customerVO);
    }
    
    /**
     * 导出excel
     */
    @AutoLog(value = "客户信息-导出")
    @ApiOperation(value="客户信息-导出", notes="客户信息-导出")
    @GetMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CrmCustomer customer) {
        return super.exportXls(request, customer, CrmCustomer.class, "客户信息");
    }
    
    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CrmCustomer.class);
    }
    
    /**
     * 生成客户编号
     * 格式：KH + 年月日 + 4位序号
     */
    private String generateCustomerCode() {
        String datePrefix = "KH" + java.time.LocalDate.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));
        
        // 查询当天最大编号
        QueryWrapper<CrmCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.likeRight("customer_code", datePrefix);
        queryWrapper.orderByDesc("customer_code");
        queryWrapper.last("limit 1");
        CrmCustomer customer = customerService.getOne(queryWrapper);
        
        int sequence = 1;
        if (customer != null && customer.getCustomerCode() != null) {
            String currentCode = customer.getCustomerCode();
            try {
                sequence = Integer.parseInt(currentCode.substring(datePrefix.length())) + 1;
            } catch (Exception e) {
                log.error("解析客户编号序列号失败", e);
            }
        }
        
        return datePrefix + String.format("%04d", sequence);
    }
    
    /**
     * 验证并补全省市区信息
     * @param customerVO 客户VO对象
     */
    private void validateAreaInfo(CrmCustomerVO customerVO) {
        // 确保省市区编码和名称匹配
        if (customerVO.getProvinceCode() != null && !customerVO.getProvinceCode().isEmpty()) {
            // 省编码存在但省名称为空，尝试获取省名称
            if (customerVO.getProvinceName() == null || customerVO.getProvinceName().isEmpty()) {
                log.warn("客户[{}]省编码存在但省名称为空", customerVO.getCustomerName());
            }
            
            // 市编码存在但市名称为空
            if (customerVO.getCityCode() != null && !customerVO.getCityCode().isEmpty() 
                && (customerVO.getCityName() == null || customerVO.getCityName().isEmpty())) {
                log.warn("客户[{}]市编码存在但市名称为空", customerVO.getCustomerName());
            }
            
            // 区编码存在但区名称为空
            if (customerVO.getAreaCode() != null && !customerVO.getAreaCode().isEmpty() 
                && (customerVO.getAreaName() == null || customerVO.getAreaName().isEmpty())) {
                log.warn("客户[{}]区编码存在但区名称为空", customerVO.getCustomerName());
            }
        }
        
        log.info("客户[{}]省市区信息: 省[{}-{}], 市[{}-{}], 区[{}-{}]", 
            customerVO.getCustomerName(),
            customerVO.getProvinceCode(), customerVO.getProvinceName(),
            customerVO.getCityCode(), customerVO.getCityName(),
            customerVO.getAreaCode(), customerVO.getAreaName());
    }
    
    /**
     * 客户名称智能提示
     * @param keyword 搜索关键字
     * @param limit 限制结果数量
     * @return 客户信息列表
     */
    @AutoLog(value = "客户信息-智能提示")
    @ApiOperation(value="客户信息-智能提示", notes="客户信息-智能提示")
    @GetMapping(value = "/suggest")
    public Result<List<CrmCustomer>> suggestList(@RequestParam(name = "keyword") String keyword,
                                               @RequestParam(name = "limit", defaultValue = "10") Integer limit) {
        List<CrmCustomer> list = customerService.getSuggestCustomerList(keyword, limit);
        log.info("执行客户名称智能提示查询，关键词: {}, 结果数量: {}", keyword, list.size());
        return Result.OK(list);
    }
    
    /**
     * 联系人智能提示
     * @param keyword 搜索关键字
     * @param limit 限制结果数量
     * @return 联系人信息列表
     */
    @AutoLog(value = "联系人-智能提示")
    @ApiOperation(value="联系人-智能提示", notes="联系人-智能提示")
    @GetMapping(value = "/suggestContact")
    public Result<List<Map<String, Object>>> suggestContactList(@RequestParam(name = "keyword") String keyword,
                                                              @RequestParam(name = "limit", defaultValue = "10") Integer limit) {
        List<Map<String, Object>> list = customerService.getSuggestContactList(keyword, limit);
        log.info("执行联系人智能提示查询，关键词: {}, 结果数量: {}", keyword, list.size());
        return Result.OK(list);
    }
    
    /**
     * 检查客户名称相似度
     * @param customerVO 客户信息
     * @return 相似客户列表
     */
    @AutoLog(value = "客户信息-相似度检查")
    @ApiOperation(value="客户信息-相似度检查", notes="客户信息-相似度检查")
    @PostMapping(value = "/checkSimilarity")
    public Result<List<Map<String, Object>>> checkSimilarity(@RequestBody CrmCustomerVO customerVO) {
        List<Map<String, Object>> similarCustomers = customerService.checkCustomerSimilarity(customerVO);
        log.info("执行客户相似度检查，客户名称: {}, 找到相似客户: {}", customerVO.getCustomerName(), similarCustomers.size());
        return Result.OK(similarCustomers);
    }
    
    /**
     * 检查客户名称和联系人组合是否已存在
     * @param customerVO 客户信息
     * @return 检查结果
     */
    @AutoLog(value = "客户信息-检查唯一性")
    @ApiOperation(value="客户信息-检查唯一性", notes="客户信息-检查唯一性")
    @PostMapping(value = "/checkUnique")
    public Result<?> checkUnique(@RequestBody CrmCustomerVO customerVO) {
        try {
            if (customerVO.getCustomerName() == null || customerVO.getCustomerName().trim().isEmpty() ||
                customerVO.getContactPerson() == null || customerVO.getContactPerson().trim().isEmpty()) {
                return Result.error("客户名称和联系人不能为空");
            }
            
            // 构建查询条件
            QueryWrapper<CrmCustomer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("customer_name", customerVO.getCustomerName().trim())
                      .eq("contact_person", customerVO.getContactPerson().trim())
                      .eq("del_flag", 0);
            
            // 如果是编辑模式，排除当前客户
            if (customerVO.getId() != null && !customerVO.getId().trim().isEmpty()) {
                queryWrapper.ne("id", customerVO.getId());
            }
            
            Long count = customerService.count(queryWrapper);
            
            if (count > 0) {
                return Result.error("客户名称[" + customerVO.getCustomerName() + "]和联系人[" + customerVO.getContactPerson() + "]组合已存在");
            } else {
                return Result.OK("可以使用");
            }
        } catch (Exception e) {
            log.error("检查客户唯一性失败", e);
            return Result.error("检查失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有客户列表
     * @return 客户信息列表
     */
    @AutoLog(value = "客户信息-获取所有列表")
    @ApiOperation(value="客户信息-获取所有列表", notes="客户信息-获取所有列表")
    @GetMapping(value = "/listAll")
    public Result<List<CrmCustomer>> listAll() {
        QueryWrapper<CrmCustomer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag", 0);
        queryWrapper.orderByAsc("customer_name");
        List<CrmCustomer> list = customerService.list(queryWrapper);
        log.info("获取所有客户列表，返回记录数：{}", list.size());
        return Result.OK(list);
    }
} 